package com.fdb.efp.console.api;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.Optional;
import java.util.stream.Stream;

@Aspect
@Component
public class ValidateAspect {
	
	private static Logger logger = LoggerFactory.getLogger(ValidateAspect.class);
	
	@Around("execution(* com.fdb.efp.console.api.rest..*.*"
			+ "(..,org.springframework.validation.BindingResult,..,java.lang.Exception))")
	public Object validateControllerMethod(ProceedingJoinPoint jp) throws Throwable {
		Optional<BindingResult> ex = Stream.of(jp.getArgs()).filter(BindingResult.class::isInstance)
				.map(BindingResult.class::cast)
				.filter(BindingResult::hasErrors).findFirst();
		if (ex.isPresent()) {
			BindingResult result = ex.get();
			FieldError error = result.getFieldError();
			String errMsg = "";
			if (error != null) {
				errMsg = "对象：" + result.getObjectName() + "的字段：" + error.getField() 
				+ error.getDefaultMessage() + ", 当前值：" + error.getRejectedValue();
				logger.error(errMsg);
			}
			int argsSize = jp.getArgs().length;
			jp.getArgs()[argsSize - 1] = new Exception(errMsg);
		}
		return jp.proceed(jp.getArgs()); 
	}
}
